package com.fone.player.activity.personal;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.text.format.Formatter;
import android.util.DisplayMetrics;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.fone.player.R;
import com.fone.player.activity.BaseActivity;
import com.fone.player.activity.personal.adapter.CacheGridAdatper;
import com.fone.player.activity.personal.adapter.CacheGridVarietyAdatper;
import com.fone.player.activity.personal.adapter.CacheListAdatper;
import com.fone.player.activity.personal.adapter.CacheManageListAdatper;
import com.fone.player.activity.personal.adapter.CacheTvPageAdapter;
import com.fone.player.bean.MemoryData;
import com.fone.player.client.Callback;
import com.fone.player.client.DramaRst;
import com.fone.player.client.DramaRst.Cnts;
import com.fone.player.client.Error;
import com.fone.player.client.Reporter;
import com.fone.player.client.Request;
import com.fone.player.constant.FoneConstant;
import com.fone.player.entity.CacheVideo;
import com.fone.player.entity.OfflineCache;
import com.fone.player.play.PlayerFrom;
import com.fone.player.storage.SharedPreferenceModule;
import com.fone.player.storage.StorageModule;
import com.fone.player.storage.download.DownloadUtil;
import com.fone.player.util.FoneUtil;
import com.fone.player.util.L;
import com.fone.player.util.SystemUtil;
import com.fone.player.view.ChangeTempLimitDialog;
import com.fone.player.view.WaitingDialog;
import com.fone.player.widget.xlistview.XListView;
import com.fone.player.widget.xlistview.XListView.IXListViewListener;

import de.greenrobot.event.EventBus;

/**
 * 缓存模块(和收藏模块基本一致)
 * 
 * 
 * @author JasonZue
 * @since 2014-4-22
 */

public class CacheActivity extends BaseActivity implements OnClickListener,
		IXListViewListener, OnScrollListener {

	private static final String TAG = "CacheActivity";

	private Context mContext;
	private Handler mHandler;

	private TextView mTitleTv;
	private Button mLeftBt, mRightBt;

	private CheckBox mAutoDownloadCb;
	private XListView mCacheListView;
	private GridView mCacheGridView;// 规则剧集
	private GridView mCacheGridVarietyView;// 非规则剧集

	private TextView mAvailableStroageTv, mDownloadTextTv;
	// 全选,删除,更多剧集
	private Button mSelectAllBt, mDeleteBt, mDownloadMoreBt;
	private LinearLayout mDeleteLl;
	private RelativeLayout mAutoCacheRl, mStorageInfoRl, mStorageRl, mNodateRl;
	private RelativeLayout mWaitingRl;
	private HorizontalScrollView mPageInfoSv;
	private ProgressBar mStoragePb;
	private EditText mLimitEt;

	private CacheListAdatper mOfflineCacheFolderAdatper,
			mOfflineCacheFileAdapter;
	private CacheManageListAdatper mOfflineCacheFolderManageAdatper,
			mOfflineCacheFileManageAdatper;// 缓存管理adapter,电视剧缓存管理adapter
	private CacheGridAdatper mGridAdatper;// 规则剧集adapter
	private CacheGridVarietyAdatper mGridVarityAdatper; // 非剧集adapter

	private CacheTvPageAdapter mPageAdapter;// 分页adapter

	private GridView mPageGridView;// 分页listview

	private List<OfflineCache> mOfflineCacheFolderList = new ArrayList<OfflineCache>();// 缓存列表使用的数据
	private List<OfflineCache> mOfflineCacheFileList = new ArrayList<OfflineCache>();// 缓存电视剧列表使用的数据
	private List<OfflineCache> mCacheTVSelectionData = new ArrayList<OfflineCache>();// 缓存电视剧列表使用的数据

	private boolean isSelectedAll = false;
	public int ViewMode = NORMAL_MODE;
	public static final int NORMAL_MODE = 1; // 普通界面模式
	public static final int MANAGEMENT_MODE = 2;// 管理界面模式
	public static final int TV_SERISE_MODE = 3;// 电视剧界面模式
	public static final int TV_SELECT_MODE = 4;// 电视剧缓存选择模式
	public static final int TV_MANAGEMENT_MODE = 5;// 电视剧管理界面模式
	public static final int CHANGE_PAGE = 6;// 分页选择时切换分页对应数据
	public static final int DOWNLOAD_WHILE_PLAY = 7;// 边播边下
	public static final int MEMORY_LIMIT_FULL = 8;// 存储空间满
	public static final int UPDATE_MEMORY = 9;// 更新存储空间

	public static final int EVENTBUS_WAITING = 1;// 刷新界面等待
	public static final int REQUEST_WAITING = 2;// 请求更多数据等待
	public static final int DELETE_WAITING = 3;// 删除界面等待
	public static final int CHANGE2TV_WAITING = 4;// 跳转TV界面等待
	public static final int DEFAULT_WAITING = 0;// 默认情况

	private int selectedPageNum = 0;// 记录选中分页
	// private SharedPreferences mSp;
	private long mBaseItem;
	private int selectedCount;//
	private int tvSelectedCount;//
	private String mDramaUrl = "";// 剧集请求接口
	private String mDramaName = "";// 剧集名称
	private String mSourceName = "";// 来源名称(土豆,优酷)
	private long dramaCCID = -1;
	private boolean isRegular = true;// 记录是否为规则剧集(默认规则)
	private int mWaitingFlag = DEFAULT_WAITING;
	private boolean isDeleting = false;// 删除标记
	private boolean isMounted;

	private DramaCallback dramaCallback;
	private List<Cnts> mHorizontalDate = new ArrayList<DramaRst.Cnts>();
	private WaitingDialog dialog;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mContext = getApplicationContext();
		// mSp = mContext.getSharedPreferences(FoneConstant.FONE_SP_NAME_SP,
		// Activity.MODE_PRIVATE);
		setContentView(R.layout.personal_cache_view);
		StorageModule.getInstance().startSendOfflineCacheMessage();
		initHandler();
		initView();
		EventBus.getDefault().register(this);
		initData();

	}

	/**
	 * 初始化handler
	 * 
	 * @return void
	 * @throws
	 */
	@SuppressLint("HandlerLeak")
	private void initHandler() {
		mHandler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				super.handleMessage(msg);
				switch (msg.what) {
				case TV_SERISE_MODE:
					// 获取电视剧数据
					L.v("JasonZue",
							"time of arrived in TV_SERISE_MODE from NORMAL_MODE(handler):"
									+ System.currentTimeMillis());
					OfflineCache mTvOfflineCache = (OfflineCache) msg.obj;
					mDramaName = mTvOfflineCache.getCacheName();
					L.v("JasonZue", "第一层数据" + mTvOfflineCache.toString());
					// mWaitingRl.setVisibility(View.VISIBLE);
					showWaiting(EVENTBUS_WAITING);
					mDramaUrl = mTvOfflineCache.getCacheDramaUrl();
					mSourceName = mTvOfflineCache.getCacheSourceName();
					getTvSeriseData(mTvOfflineCache);
					break;
				case CHANGE_PAGE:
					// 切换分页内容
					selectedPageNum = msg.arg1;
					// mWaitingRl.setVisibility(View.VISIBLE);
					showWaiting(REQUEST_WAITING);
					// 请求选中页数据
					String pageUrl = (String) msg.obj;
					if (pageUrl.startsWith("[host]/player")) {
						String url = pageUrl.substring(pageUrl
								.indexOf("]/player") + 8);
						if (FoneUtil.isNetOkWithToast(mContext)) {
							Request.getInstance().drama(url, dramaCallback);
						}
						L.v(TAG, "initHandler", "CHANGE_PAGE-----> url:"
								+ pageUrl);
					}
					mGridAdatper.cancleSeleted();// 清空选中状态
					mGridAdatper.notifyDataSetChanged();
					mGridVarityAdatper.cancleSeleted();
					mGridVarityAdatper.notifyDataSetChanged();
					break;
				case NetCollectionActivity.UPDATE_LIMIT_TEMP_TEXT:
					// 更新选中的容量大小
					String text = SharedPreferenceModule.getInstance()
							.getString(
									FoneConstant.TMP_LIMIT_ITEM_LONG_FLAG_SP,
									Formatter.formatFileSize(mContext,
											mBaseItem * 1));
					mLimitEt.setText(text);
					long freeSpaceSize = isMounted ? (SystemUtil.getInstance()
							.getFreeSpaceByteBySDCard()) : (SystemUtil
							.getInstance().getFreeSpaceByteByPhoneBody());

					if (freeSpaceSize > SharedPreferenceModule.getInstance()
							.getLong(FoneConstant.TMP_LIMIT_SIZE)) {
						StorageModule.getInstance()
								.startSendOfflineCacheMessage();
						StorageModule.getInstance().startAllCache();
					}
					break;
				case TV_SELECT_MODE:
					// 请求更多剧集数据(网络)
					String dramaUrl = (String) msg.obj;
					doMoreDrama(dramaUrl);
					break;
				case DOWNLOAD_WHILE_PLAY:
					// 请求边播边下
					OfflineCache cache = (OfflineCache) msg.obj;
					// 方法会崩溃
					StorageModule.getInstance().mergeCacheFilePlayableByCID(
							cache);
					String videoName = "";
					ArrayList<CacheVideo> videos = new ArrayList<CacheVideo>();
					if (cache.getCacheContentType() == OfflineCache.CACHE_CONTENT_TYPE_ANIMATION
							|| cache.getCacheContentType() == OfflineCache.CACHE_CONTENT_TYPE_TV
							|| cache.getCacheContentType() == OfflineCache.CACHE_CONTENT_TYPE_VARIETY) {
						videoName = cache.getCacheName()
								+ cache.getCacheEpisodeNum();
					} else {
						videoName = cache.getCacheName();
					}
					CacheVideo video = new CacheVideo(videoName,
							cache.getCacheXYZPlayUrl(),
							cache.getCacheImageUrl());
					video.setUrls(cache.getOfflineCacheFragmentUrlArray());
					video.setDurations(cache
							.getOfflineCacheFragmentDurationArray());
					video.setDownFinish(cache.getCacheDownloadState() == OfflineCache.CACHE_STATE_FINISH ? true
							: false);
					videos.add(video);
					L.v(TAG, "边播边下数据::" + cache.toString());
					FoneUtil.openCacheVideo(CacheActivity.this,
							PlayerFrom.CACHE_LIST, videos, 0);
					break;
				case MEMORY_LIMIT_FULL:
					// 达到上限
					FoneUtil.showToast(mContext, R.string.cache_no_memory_text);
					StorageModule.getInstance().pauseAllCache(true);
					StorageModule.getInstance().stopSendOfflineCacheMessage();
					break;
				case UPDATE_MEMORY:
					// 更新存储空间
					// MemoryData data = (MemoryData) msg.obj;
					// mAvailableStroageTv.setText("剩余存储空间" +
					// data.getSpaceLeft());
					// mStoragePb.setProgress(data.getStroagePrecents());
					L.v(TAG,
							"cacheActivity baseItem:"
									+ mBaseItem
									+ " sp choosed id: "
									+ SharedPreferenceModule
											.getInstance()
											.getInt(FoneConstant.TMP_LIMIT_CHOOSED_ID_FLAG_SP,
													R.id.rt_limit_item1));
					long baseItem = (Long) msg.obj;
					String limitSizeTextInSp = SharedPreferenceModule
							.getInstance().getString(
									FoneConstant.TMP_LIMIT_ITEM_LONG_FLAG_SP);
					if (!TextUtils.isEmpty(limitSizeTextInSp)) {
						// 可以获取到SP中显示的数据
						L.v("JasonZue", "limit data in SP is null!");
						mLimitEt.setText(limitSizeTextInSp);
					} else {
						// 从sp中获取存入的限制上限 并设置对应文字
						L.v("JasonZue", "limit data in SP isn't null!");
						switch (SharedPreferenceModule.getInstance().getInt(
								FoneConstant.TMP_LIMIT_CHOOSED_ID_FLAG_SP,
								R.id.rt_limit_item1)) {
						case R.id.rt_limit_item1:
							mLimitEt.setText(Formatter.formatFileSize(mContext,
									baseItem * 1));
							SharedPreferenceModule.getInstance().setLong(
									FoneConstant.TMP_LIMIT_SIZE, baseItem * 1);
							break;
						case R.id.rt_limit_item2:
							mLimitEt.setText(Formatter.formatFileSize(mContext,
									baseItem * 2));
							SharedPreferenceModule.getInstance().setLong(
									FoneConstant.TMP_LIMIT_SIZE, baseItem * 4);
							break;
						case R.id.rt_limit_item3:
							mLimitEt.setText(Formatter.formatFileSize(mContext,
									baseItem * 3));
							SharedPreferenceModule.getInstance().setLong(
									FoneConstant.TMP_LIMIT_SIZE, baseItem * 6);
							break;
						case R.id.rt_limit_item4:
							mLimitEt.setText(Formatter.formatFileSize(mContext,
									baseItem * 4));
							SharedPreferenceModule.getInstance().setLong(
									FoneConstant.TMP_LIMIT_SIZE, baseItem * 8);
							break;
						}
					}
					break;
				}
			}
		};
	}

	/**
	 * 初始化数据
	 * 
	 * @return void
	 * @throws
	 */

	private void initData() {

		SharedPreferenceModule.getInstance().setInt(
				FoneConstant.LAST_CACHE_COUNT_SP,
				StorageModule.getInstance().getOfflineCacheFileCount());// 存入当前缓存完毕的数量,用于显示小红点

		if (SharedPreferenceModule.getInstance().getBoolean(
				FoneConstant.IS_FIRST_USE_SP, true)) {
			FoneUtil.showToast(mContext,
					R.string.cache_dowoload_while_play_text);
			SharedPreferenceModule.getInstance().setBoolean(
					FoneConstant.IS_FIRST_USE_SP, false);
		}

		// 计算存储上限
		getAvailableStorage();

		// 初始化callback
		dramaCallback = new DramaCallback();
		// 从数据库获取缓存列表, 通过eventbus返回数据
		L.v(TAG, "我的缓存--->initData(),请求获取folder数据");
		showWaiting(EVENTBUS_WAITING);
		StorageModule.getInstance().getCacheFolderList();

	}

	/**
	 * 切换剧集时使用的数据
	 * 
	 * @return void
	 * @throws
	 */
	private void getTvSeriseData(OfflineCache tvOfflineCache) {

		ViewMode = TV_SERISE_MODE;
		if (null != tvOfflineCache) {

			StorageModule.getInstance().getCacheFileListByCCID(
					tvOfflineCache.getCacheCCID());

			dramaCCID = tvOfflineCache.getCacheCCID();

			L.v(TAG, "我的缓存--->getTvSeriseData(),请求获取file数据 ,ccid:" + dramaCCID);
		} else {
			L.v(TAG, "我的缓存--->getTvSeriseData(),请求获取file数据 ,folder层数据为空!!!! ");
		}
		showWaiting(EVENTBUS_WAITING);
	}

	/**
	 * 获取可用容量大小并设置显示
	 * 
	 * @return void
	 * @throws
	 */
	private void getAvailableStorage() {
		long time1 = System.currentTimeMillis();
		new Thread(new Runnable() {

			@Override
			public void run() {

				// 检测存储设备是否挂载
				isMounted = SystemUtil.getInstance().isSDCardMounted();

				// 计算每份的大小
				mBaseItem = isMounted ? (SystemUtil.getInstance()
						.getTotalSpaceByteBySDCard() / 16) : (SystemUtil
						.getInstance().getTotalSpaceByteByPhoneBody() / 16);

				// 更新容量大小
				StorageModule.getInstance().checkSingleStorageSpace();

				// String spaceLeft = isMounted == true ? (SystemUtil
				// .getInstance().getFreeSpaceFormatBySDCard())
				// : (SystemUtil.getInstance()
				// .getFreeSpaceFormatByPhoneBody());
				// int stroagePrecents = SystemUtil.getInstance()
				// .getFreeSpacePercent(isMounted);
				// long freeSpaceSize = isMounted == true ? (SystemUtil
				// .getInstance().getFreeSpaceByteByAllStorage())
				// : (SystemUtil.getInstance()
				// .getFreeSpaceByteByPhoneBody());
				//
				// if (freeSpaceSize < SharedPreferenceModule.getInstance()
				// .getLong(FoneConstant.TMP_LIMIT_SIZE)) {
				// if (!toastFlage) {
				// Message message = mHandler.obtainMessage();
				// message.what = MEMORY_LIMIT_FULL;
				// toastFlage = true;
				// // 暂停所有下载
				// mHandler.sendMessage(message);
				// L.v("JasonZue", "存储容量到达限制,暂停所有下载任务");
				// }
				// }
				// MemoryData memoryData = new MemoryData();
				// memoryData.setSpaceLeft(spaceLeft);
				// memoryData.setStroagePrecents(stroagePrecents);

				Message message = mHandler.obtainMessage();
				message.what = UPDATE_MEMORY;
				message.obj = mBaseItem;
				mHandler.sendMessage(message);
			}
		}).start();
		L.v(TAG, "获取容量大小耗时:" + (System.currentTimeMillis() - time1));
	}

	/**
	 * 接收返回的数据
	 * 
	 * @param msg
	 * @return void
	 * @throws
	 */
	public void onEventMainThread(Message msg) {
		Bundle bundle = null;
		switch (msg.what) {
		case StorageModule.MSG_FILE_CACHE_UPDATE_PROGRESS_SUCCESS:
			Bundle collectionBundle = msg.getData();
			if (collectionBundle != null) {
				OfflineCache offlineCache = collectionBundle
						.getParcelable(OfflineCache.OFFLINE_CACHE);
				if (offlineCache == null) {
					L.e(TAG, "onEventMainThread", "file返回为null!");
					return;
				}
				switch (ViewMode) {
				case NORMAL_MODE:
				case MANAGEMENT_MODE:
					// L.v(TAG,
					// "file列表当前在NORMAL_MODE 获取的数据：" + "name="
					// + offlineCache.getCacheName()
					// + offlineCache.getCacheEpisodeNum()
					// + " downloadState="
					// + offlineCache.getCacheDownloadState());
					break;
				case TV_SERISE_MODE:

					// L.v(TAG,
					// "offlineCache file TV_SERISE_MODE name="
					// + offlineCache.getCacheName()
					// + offlineCache.getCacheEpisodeNum()
					// + " downloadState="
					// + offlineCache.getCacheDownloadState());
					if (offlineCache != null) {

						mNodateRl.setVisibility(View.GONE);

						// 更新进度
						mOfflineCacheFileList = mOfflineCacheFileAdapter
								.setOfflineCache(offlineCache);

						// fix 4325 防止数据不同步时 显示问题
						if (mOfflineCacheFileList != null
								&& mOfflineCacheFileList.size() > 0) {
							mDownloadMoreBt.setVisibility(View.VISIBLE);
							mRightBt.setVisibility(View.VISIBLE);

							mOfflineCacheFileManageAdatper
									.setOfflineCacheList(mOfflineCacheFileList);
							mOfflineCacheFileManageAdatper
									.notifyDataSetChanged();
						} else {
							mDownloadMoreBt.setVisibility(View.GONE);
							mRightBt.setVisibility(View.INVISIBLE);
						}
					}
					cancelWaiting(CHANGE2TV_WAITING);
					break;
				case TV_MANAGEMENT_MODE:
					break;
				}
			}
			cancelWaiting(EVENTBUS_WAITING);
			break;
		case StorageModule.MSG_FOLDER_CACHE_UPDATE_PROGRESS_SUCCESS:
			Bundle folderBundle = msg.getData();
			if (folderBundle != null) {
				OfflineCache offlineCache = folderBundle
						.getParcelable(OfflineCache.OFFLINE_CACHE);
				if (offlineCache == null) {
					L.e(TAG, "onEventMainThread", "file返回为null!");
				}

				switch (ViewMode) {
				case NORMAL_MODE:
					// L.v(TAG,
					// "folder列表当前在NORMAL_MODE 获取的数据 " + "name="
					// + offlineCache.getCacheName()
					// + offlineCache.getCacheEpisodeNum()
					// + " downloadState="
					// + offlineCache.getCacheDownloadState());
					if (offlineCache != null) {
						mNodateRl.setVisibility(View.GONE);
						mRightBt.setVisibility(View.VISIBLE);
						// mCacheData.clear();
						// mCacheData.addAll(cacheFolderList);
						mOfflineCacheFolderManageAdatper.notifyDataSetChanged();
						// 更新进度
						mOfflineCacheFileList = mOfflineCacheFolderAdatper
								.setOfflineCache(offlineCache);
					}
					// else {
					// mNodateRl.setVisibility(View.VISIBLE);
					// mRightBt.setVisibility(View.GONE);
					// }
					cancelWaiting(EVENTBUS_WAITING);
					break;
				case MANAGEMENT_MODE:
					break;
				case TV_SERISE_MODE:
				case TV_MANAGEMENT_MODE:
					// L.v("JasonZue",
					// "folder列表 当前在TV_SERISE_MODE 获取的数据：" + "name="
					// + offlineCache.getCacheName()
					// + offlineCache.getCacheEpisodeNum()
					// + " downloadState="
					// + offlineCache.getCacheDownloadState());
					break;
				}
			}
			cancelWaiting(EVENTBUS_WAITING);
			break;
		case StorageModule.MSG_FOLDER_CACHE_LIST_SUCCESS:
			// 从数据库获取缓存列表, 通过eventbus返回数据
			bundle = msg.getData();
			if (bundle == null) {
				cancelWaiting(EVENTBUS_WAITING);
				return;
			}

			ArrayList<OfflineCache> offlineCacheFolderList = bundle
					.getParcelableArrayList(OfflineCache.OFFLINE_CACHE_LIST);
			if (offlineCacheFolderList != null
					&& offlineCacheFolderList.size() > 0) {

				mOfflineCacheFolderList = offlineCacheFolderList;

				if (mOfflineCacheFolderList != null
						&& mOfflineCacheFolderList.size() > 0) {
					mNodateRl.setVisibility(View.GONE);
					mRightBt.setVisibility(View.VISIBLE);
					mOfflineCacheFolderManageAdatper.notifyDataSetChanged();
					mOfflineCacheFolderAdatper
							.setOfflineCacheList(mOfflineCacheFolderList);
					mOfflineCacheFolderAdatper.notifyDataSetChanged();
				} else {
					mNodateRl.setVisibility(View.VISIBLE);
					mRightBt.setVisibility(View.GONE);
				}
			} else {
				mNodateRl.setVisibility(View.VISIBLE);
				mRightBt.setVisibility(View.GONE);
			}
			cancelWaiting(EVENTBUS_WAITING);
			break;
		case StorageModule.MSG_FILE_CACHE_LIST_SUCCESS:
			bundle = msg.getData();
			if (bundle == null) {
				cancelWaiting(EVENTBUS_WAITING);
				return;
			}

			ArrayList<OfflineCache> offlineCacheFileList = bundle
					.getParcelableArrayList(OfflineCache.OFFLINE_CACHE_LIST);
			if (offlineCacheFileList != null && offlineCacheFileList.size() > 0) {
				mOfflineCacheFileList = offlineCacheFileList;
			}

			change2TvList();
			cancelWaiting(EVENTBUS_WAITING);
			break;
		case StorageModule.MSG_DELETE_CACHE_SUCCESS:
			isDeleting = false;
			L.v("JasonZue", "删除成功后的删除状态:" + isDeleting);
			if (ViewMode == MANAGEMENT_MODE) {
				L.v("JasonZue",
						"eventBus获取到删除成功,当前模式:MANAGEMENT_MODE,获取folder数据");
				StorageModule.getInstance().getCacheFolderList();

				if (mOfflineCacheFolderList.size() == 0) {
					mNodateRl.setVisibility(View.VISIBLE);
				}
			} else if (ViewMode == TV_MANAGEMENT_MODE) {
				L.v("JasonZue",
						"eventBus获取到删除成功,当前模式:TV_MANAGEMENT_MODE,获取file数据,CCID:"
								+ dramaCCID);
				if (mOfflineCacheFileList.size() == 0) {
					mNodateRl.setVisibility(View.VISIBLE);
				}

				// 刷新数据
				StorageModule.getInstance().getCacheFileListByCCID(dramaCCID);

				L.v(TAG, "删除成功后的数据数量:" + mOfflineCacheFileList.size());
			}
			cancelWaiting(DELETE_WAITING);
			FoneUtil.showToast(mContext, R.string.cache_delete_success_text);
			break;
		case StorageModule.MSG_STORAGE_SPACE_PROGRESS:
			// 更新存储空间
			MemoryData data = (MemoryData) msg.obj;
			mAvailableStroageTv.setText("剩余存储空间" + data.getSpaceLeft());
			mStoragePb.setProgress(data.getStroagePrecents());
			break;
		}
	}

	private void initView() {

		mLeftBt = (Button) findViewById(R.id.common_title_left_bt);
		mRightBt = (Button) findViewById(R.id.common_title_right_bt);
		mTitleTv = (TextView) findViewById(R.id.common_title_text_tv);
		mDownloadMoreBt = (Button) findViewById(R.id.cache_download_more_bt);

		mAutoDownloadCb = (CheckBox) findViewById(R.id.cache_auto_download_cb);
		mCacheListView = (XListView) findViewById(R.id.cache_lv);
		mCacheGridView = (GridView) findViewById(R.id.cache_tv_gv);
		mCacheGridVarietyView = (GridView) findViewById(R.id.cache_tv_variety_gv);
		mAvailableStroageTv = (TextView) findViewById(R.id.cache_useable_storage_text);
		mDownloadTextTv = (TextView) findViewById(R.id.cache_download_switch_text);
		mStoragePb = (ProgressBar) findViewById(R.id.cache_avalible_storage_pb);
		mSelectAllBt = (Button) findViewById(R.id.cache_select_all_bt);
		mDeleteBt = (Button) findViewById(R.id.cache_delete_bt);
		mDeleteLl = (LinearLayout) findViewById(R.id.cache_delete_ll);
		mStorageInfoRl = (RelativeLayout) findViewById(R.id.cache_storage_login_rl);
		mAutoCacheRl = (RelativeLayout) findViewById(R.id.cache_auto_download_switch_rl);
		mStorageRl = (RelativeLayout) findViewById(R.id.cache_storage_left_info_rl);
		mNodateRl = (RelativeLayout) findViewById(R.id.personal_cache_nodate_rl);
		mPageInfoSv = (HorizontalScrollView) findViewById(R.id.cache_page_hsv);
		mLimitEt = (EditText) findViewById(R.id.cache_storage_limit_et);
		mWaitingRl = (RelativeLayout) findViewById(R.id.cache_waiting_rl);

		mPageGridView = (GridView) findViewById(R.id.cache_gridview);
		mPageAdapter = new CacheTvPageAdapter(mContext, mHorizontalDate,
				selectedPageNum, mHandler);
		mPageGridView.setAdapter(mPageAdapter);

		// 下载界面
		mOfflineCacheFolderAdatper = new CacheListAdatper(mContext, mHandler);// 使用的普通列表数据
		mOfflineCacheFolderAdatper.setListView(mCacheListView);
		mOfflineCacheFileAdapter = new CacheListAdatper(mContext, mHandler);// 使用的电视剧列表数据
		mOfflineCacheFileAdapter.setListView(mCacheListView);

		// 管理界面
		mOfflineCacheFolderManageAdatper = new CacheManageListAdatper(mContext);// 使用的普通列表数据
		mOfflineCacheFileManageAdatper = new CacheManageListAdatper(mContext);// 使用的是电视剧列表数据
		mGridAdatper = new CacheGridAdatper(mContext, mCacheTVSelectionData);// 使用该电视剧最新所有选集数据(服务器请求)规则
		mGridVarityAdatper = new CacheGridVarietyAdatper(mContext,
				mCacheTVSelectionData);// 使用该综艺最新所有选集数据(服务器请求)非规则
		mCacheListView.setAdapter(mOfflineCacheFolderAdatper);
		mCacheListView.setPullRefreshEnable(false);
		mCacheListView.setPullLoadEnable(false);
		mCacheListView.setEnableDragLoadMore(false);
		mCacheListView.setXListViewListener(this);
		mCacheListView.setOnScrollListener(this);

		mLeftBt.setText(getResources().getString(R.string.cache_title_text));
		mRightBt.setText(getResources().getString(
				R.string.cache_title_right_delete_text));
		mTitleTv.setVisibility(View.GONE);

		mLeftBt.setOnClickListener(this);
		mRightBt.setOnClickListener(this);
		mSelectAllBt.setOnClickListener(this);
		mDeleteBt.setOnClickListener(this);
		mDownloadMoreBt.setOnClickListener(this);
		mLimitEt.setOnClickListener(this);
		dialog = new WaitingDialog(mContext, CacheActivity.this);

		boolean isWifiChecked = SharedPreferenceModule.getInstance()
				.getBoolean(FoneConstant.AUTO_DOWNLOAD_FLAG_SP, true);
		mAutoDownloadCb.setChecked(isWifiChecked);
		mAutoDownloadCb
				.setOnCheckedChangeListener(new OnCheckedChangeListener() {

					@Override
					public void onCheckedChanged(CompoundButton buttonView,
							boolean isChecked) {
						// 处理开启自动下载功能
						SharedPreferenceModule.getInstance().setBoolean(
								FoneConstant.AUTO_DOWNLOAD_FLAG_SP, isChecked);
						if (!isChecked) {
							FoneUtil.showToast(
									mContext,
									R.string.cache_wifi_download_only_close_text);
							// startAllCache();
						} else {
							FoneUtil.showToast(mContext,
									R.string.cache_wifi_download_only_open_text);
							if (StorageModule.MSG_WIFI_NETWORK_TYPE != DownloadUtil
									.getNetType()) {
								// 如果当前不是WIFI网络,暂停所有缓存内容
								StorageModule.getInstance().pauseAllCache(true);
							}
						}

					}
				});

		mCacheListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// 处理条目点击事件
				CheckBox mBox = (CheckBox) view
						.findViewById(R.id.cache_is_selected_cb);

				try {
					switch (ViewMode) {
					case NORMAL_MODE:
						// 缓存界面
						if (null != mOfflineCacheFolderList.get(position - 1)
								&& (mOfflineCacheFolderList.get(position - 1)
										.getCacheContentType() == OfflineCache.CACHE_CONTENT_TYPE_TV
										|| mOfflineCacheFolderList.get(
												position - 1)
												.getCacheContentType() == OfflineCache.CACHE_CONTENT_TYPE_ANIMATION || mOfflineCacheFolderList
										.get(position - 1)
										.getCacheContentType() == OfflineCache.CACHE_CONTENT_TYPE_VARIETY)) {
							// 如果为电视剧集,点击条目跳转到剧集列表
							Message message = mHandler
									.obtainMessage(TV_SERISE_MODE);
							OfflineCache cache = mOfflineCacheFolderList
									.get(position - 1);
							message.obj = cache;
							mHandler.sendMessage(message);
							L.v("JasonZue",
									"time of jump to TV_SERISE_MODE from NORMAL_MODE:"
											+ System.currentTimeMillis());
							showWaiting(CHANGE2TV_WAITING);
						} else if (null != mOfflineCacheFolderList
								.get(position - 1)
								&& mOfflineCacheFolderList.get(position - 1)
										.getCacheDownloadState() == OfflineCache.CACHE_STATE_FINISH) {
							// 已缓存完毕 点击跳转播放
							OfflineCache currentOfflineCache = mOfflineCacheFolderList
									.get(position - 1);
							L.v(TAG, "OnItemClick:", "跳转播放之前STROAGE返回数据(处理前):"
									+ currentOfflineCache.toString());
							// 已完成的非剧集集合
							OfflineCache offlineCache = StorageModule
									.getInstance().getCacheFile(
											currentOfflineCache.getCacheCID());
							if (offlineCache != null) {

								ArrayList<OfflineCache> finishedVideos = new ArrayList<OfflineCache>();

								finishedVideos.add(offlineCache);

								openSeletedVideoBySortIndex(
										currentOfflineCache, finishedVideos);
							} else {
								L.e(TAG, "onItemClick", "offlineCache=null");
							}
						}
						break;
					case MANAGEMENT_MODE:
						// 在管理界面 点击修改删除勾选状态
						updateManagerDeleteInfo(position, mBox,
								mOfflineCacheFolderList, selectedCount);
						break;
					case TV_SERISE_MODE:
						// 剧集列表模式
						if (null != mOfflineCacheFileList.get(position - 1)
								&& mOfflineCacheFileList.get(position - 1)
										.getCacheDownloadState() == OfflineCache.CACHE_STATE_FINISH) {
							// 已缓存完毕 点击跳转播放
							OfflineCache currentOfflineCache = mOfflineCacheFileList
									.get(position - 1);
							L.v(TAG, "OnItemClick:", "跳转播放之前STROAGE返回数据(处理前):"
									+ currentOfflineCache.toString());
							// 已完成的剧集集合
							ArrayList<OfflineCache> finishedVideos = StorageModule
									.getInstance()
									.getCacheFileListStateFinishDramaByOfflineCache(
											mOfflineCacheFileList
													.get(position - 1));
							openSeletedVideoBySortIndex(currentOfflineCache,
									finishedVideos);
						}
						break;
					case TV_MANAGEMENT_MODE:
						// 剧集管理列表模式
						updateManagerDeleteInfo(position, mBox,
								mOfflineCacheFileList, tvSelectedCount);
						break;
					}
				} catch (Exception e) {
					e.printStackTrace();
					L.e(TAG, "out of index", "cacheActivity onItemClick");
				}
			}
		});

		mCacheGridView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {

				int status = mCacheTVSelectionData.get(position)
						.getCacheDownloadState();
				if (status == OfflineCache.CACHE_STATE_NOT_DOWNLOAD) {
					L.v("JasonZue", "执行了onItem,position:" + position);
					mGridAdatper.setSeclection(position);
					mGridAdatper.notifyDataSetChanged();
					if (mGridAdatper.getSelectedCount() != 0) {
						mDeleteBt.setText("确定("
								+ mGridAdatper.getSelectedCount() + ")");
						mDeleteBt.setTextColor(mContext.getResources()
								.getColor(R.color.btn_pressed_text_color));
					} else {
						mDeleteBt.setText("确定");
						mDeleteBt.setTextColor(mContext.getResources()
								.getColor(R.color.btn_unpress_text_color));
					}
				} else if (status == OfflineCache.CACHE_STATE_FINISH) {
					Toast.makeText(mContext, "已经下载完咯~", Toast.LENGTH_SHORT)
							.show();
				} else {
					Toast.makeText(mContext, "已经在下载列表中了..", Toast.LENGTH_SHORT)
							.show();
				}

			}
		});
		mCacheGridVarietyView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				int status = mCacheTVSelectionData.get(position)
						.getCacheDownloadState();
				if (status == OfflineCache.CACHE_STATE_NOT_DOWNLOAD) {
					L.v("JasonZue", "执行了onItem,position:" + position);
					mGridVarityAdatper.setSeclection(position);
					mGridVarityAdatper.notifyDataSetChanged();
					if (mGridVarityAdatper.getSelectedCount() != 0) {
						mDeleteBt.setText("确定("
								+ mGridVarityAdatper.getSelectedCount() + ")");
						mDeleteBt.setTextColor(mContext.getResources()
								.getColor(R.color.btn_pressed_text_color));
					} else {
						mDeleteBt.setText("确定");
						mDeleteBt.setTextColor(mContext.getResources()
								.getColor(R.color.btn_unpress_text_color));
					}
				} else if (status == OfflineCache.CACHE_STATE_FINISH) {
					Toast.makeText(mContext, "已经下载完咯~", Toast.LENGTH_SHORT)
							.show();
				} else {
					Toast.makeText(mContext, "已经在下载列表中了..", Toast.LENGTH_SHORT)
							.show();
				}
			}
		});

	}

	/**
	 * 更新分页选择滑动条
	 * 
	 * @return void
	 * @throws
	 */
	public void refreshPageView() {
		mPageAdapter.notifyDataSetChanged();
		mPageGridView.setNumColumns(mHorizontalDate.size());
		DisplayMetrics dm = mContext.getResources().getDisplayMetrics();
		// width是否也需要取余
		LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
				(int) (78 * dm.density * mHorizontalDate.size()),
				(int) (60 * dm.density));
		mPageGridView.setLayoutParams(params);
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {

		if (keyCode == KeyEvent.KEYCODE_BACK) {
			returnBtManage();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.common_title_left_bt:
			// 返回按钮操作事件处理
			returnBtManage();
			break;

		case R.id.common_title_right_bt:
			// 管理按钮
			doManageView();
			break;

		case R.id.cache_select_all_bt:
			// 全选按钮(在管理模式下)
			doSeleteAll();
			break;

		case R.id.cache_delete_bt:
			// 删除按钮
			doDelete();
			break;

		case R.id.cache_download_more_bt:
			// 点击下载更多按钮,切换至对应的剧集选择视图
			Reporter.logEvent(Reporter.EventId.DNLD_MORE_BTN);
			Message msg = mHandler.obtainMessage(TV_SELECT_MODE);
			msg.obj = mDramaUrl;
			mHandler.sendMessage(msg);
			break;
		case R.id.cache_storage_limit_et:
			// 点击存储空间
			new ChangeTempLimitDialog(mContext, this, mHandler);
			break;

		default:
			break;
		}

	}

	/**
	 * 处理管理按钮点击操作
	 * 
	 * @return void
	 * @throws
	 */
	private void doManageView() {
		switch (ViewMode) {
		case NORMAL_MODE:
			// 普通模式 点击删除跳转到管理模式
			change2Manage();
			break;
		case TV_SERISE_MODE:
			// 电视剧模式 点击删除跳转到对应剧集管理模式
			change2TVManage();
			// 清除选中数据
			if (mOfflineCacheFileList.size() == selectedCount) {
				mSelectAllBt.setText(getResources().getString(
						R.string.cache_cancel_all_text));
				isSelectedAll = true;
			} else {
				mSelectAllBt.setText(getResources().getString(
						R.string.cache_select_all_text));
				isSelectedAll = false;
			}
			for (int i = 0; i < mOfflineCacheFileList.size(); i++) {
				mOfflineCacheFileList.get(i).setCacheIsDelete(false);
			}
			break;
		case MANAGEMENT_MODE:
			// 管理模式 点击跳转到普通模式
			if (!isDeleting) {
				change2Normal();
				// 清除选中数据
				if (mOfflineCacheFolderList.size() == selectedCount) {
					mSelectAllBt.setText(getResources().getString(
							R.string.cache_cancel_all_text));
				} else {
					mSelectAllBt.setText(getResources().getString(
							R.string.cache_select_all_text));
					isSelectedAll = false;
				}
				for (int i = 0; i < mOfflineCacheFolderList.size(); i++) {
					mOfflineCacheFolderList.get(i).setCacheIsDelete(false);
				}
			} else {
				FoneUtil.showToast(mContext,
						R.string.cache_delete_now_please_wait_text);
			}

			break;
		case TV_MANAGEMENT_MODE:
			// 电视剧管理模式 点击删除跳转到电视剧列表
			if (!isDeleting) {
				change2TvList();
			} else {
				FoneUtil.showToast(mContext,
						R.string.cache_delete_now_please_wait_text);
			}

			break;

		}
	}

	/**
	 * 全选操作
	 * 
	 * @return void
	 * @throws
	 */
	private void doSeleteAll() {
		switch (ViewMode) {
		case MANAGEMENT_MODE:
			managementViewSelectAll(mOfflineCacheFolderManageAdatper,
					mOfflineCacheFolderList);
			break;
		case TV_SELECT_MODE:
			// 在tvGrid模式下
			// 去掉勾选状态
			if (isRegular) {
				if (mGridAdatper.getSelectedCount() > 0) {
					mGridAdatper.cancleSeleted();
					mGridAdatper.notifyDataSetChanged();
					mDeleteBt.setText("确定");
					mDeleteBt.setTextColor(mContext.getResources().getColor(
							R.color.btn_unpress_text_color));
				} else {
					change2TvList();
				}
			} else {
				if (mGridVarityAdatper.getSelectedCount() > 0) {
					mGridVarityAdatper.cancleSeleted();
					mGridVarityAdatper.notifyDataSetChanged();
					mDeleteBt.setText("确定");
					mDeleteBt.setTextColor(mContext.getResources().getColor(
							R.color.btn_unpress_text_color));
				} else {
					change2TvList();
				}
			}
			break;
		case TV_MANAGEMENT_MODE:
			// 在电视管理模式下
			managementViewSelectAll(mOfflineCacheFileManageAdatper,
					mOfflineCacheFileList);
			break;
		}
	}

	/**
	 * 处理管理页面的全选按钮操作
	 * 
	 * @param listAdatper
	 *            对应更新的adapter
	 * @param data
	 *            原始数据
	 */
	private void managementViewSelectAll(CacheManageListAdatper listAdatper,
			List<OfflineCache> data) {

		if (data.size() > 0) {
			for (int i = 0; i < data.size(); i++) {
				if (!isSelectedAll) {
					data.get(i).setCacheIsDelete(true);
				} else {
					data.get(i).setCacheIsDelete(false);
				}
			}
			isSelectedAll = !isSelectedAll;
			if (isSelectedAll) {
				mSelectAllBt.setText(getResources().getString(
						R.string.cache_cancel_all_text));
				mDeleteBt.setText(getResources().getString(
						R.string.cache_title_right_delete_text)
						+ "(" + data.size() + ")");
				mDeleteBt.setTextColor(mContext.getResources().getColor(
						R.color.btn_pressed_text_color));
			} else {
				mSelectAllBt.setText(getResources().getString(
						R.string.cache_select_all_text));
				mDeleteBt.setText(getResources().getString(
						R.string.cache_title_right_delete_text));
				mDeleteBt.setTextColor(mContext.getResources().getColor(
						R.color.btn_unpress_text_color));
			}
			listAdatper.notifyDataSetChanged();
		} else {
			FoneUtil.showToast(mContext, R.string.cache_list_is_empty_text);
		}

	}

	/**
	 * 处理删除操作(包括电视剧集9宫格添加确认处理)
	 * 
	 * @return void
	 * @throws
	 */
	private void doDelete() {
		isSelectedAll = false;
		switch (ViewMode) {
		case MANAGEMENT_MODE:
			List<OfflineCache> normalDeleteList = new ArrayList<OfflineCache>();
			for (int i = mOfflineCacheFolderList.size(); i > 0; i--) {
				if (mOfflineCacheFolderList.get(i - 1).getCacheIsDelete()) {

					OfflineCache offlineCache = mOfflineCacheFolderList
							.get(i - 1);

					if (offlineCache != null) {

						switch (offlineCache.getCacheContentType()) {
						case OfflineCache.CACHE_CONTENT_TYPE_ANIMATION:
						case OfflineCache.CACHE_CONTENT_TYPE_TV:
						case OfflineCache.CACHE_CONTENT_TYPE_VARIETY:
							// 剧集
							normalDeleteList.addAll(offlineCache
									.getOfflineCacheList());
							break;
						default:
							// 非剧集
							normalDeleteList.add(offlineCache);
							break;
						}

					}

					mOfflineCacheFolderList.remove(i - 1);
				}
			}

			if (normalDeleteList.size() == 0) {
				FoneUtil.showToast(mContext,
						R.string.cache_no_seleted_video_text);
				return;
			}
			isDeleting = true;// 删除操作标记 (用于处理返回键屏蔽)
			L.v(TAG,
					"doDelete():MANAGEMENT_MODE删除的数据:"
							+ normalDeleteList.toString());
			StorageModule.getInstance().deleteCacheList(normalDeleteList);
			showWaiting(DELETE_WAITING);

			mDeleteBt.setText(getResources().getString(
					R.string.cache_title_right_delete_text));
			mDeleteBt.setTextColor(mContext.getResources().getColor(
					R.color.btn_unpress_text_color));
			mSelectAllBt.setText(getResources().getString(
					R.string.cache_select_all_text));
			break;
		case TV_SELECT_MODE:
			// 剧集选择下载界面 按钮是确定添加下载
			if (!FoneUtil.isNetOkWithToast(mContext)) {
				return;
			}
			if (!mCacheTVSelectionData.get(0).getCacheIsDownloadable()) {
				FoneUtil.showToast(mContext,
						R.string.cache_cannot_download_try_later_text);
				return;
			}
			List<OfflineCache> tmpAddCacheList = new ArrayList<OfflineCache>();
			Iterator<Entry<Integer, String>> iterator;
			if (isRegular) {
				iterator = mGridAdatper.getSeletedMap().entrySet().iterator();
			} else {
				iterator = mGridVarityAdatper.getSeletedMap().entrySet()
						.iterator();
			}
			while (iterator.hasNext()) {

				Entry<Integer, String> entry = iterator.next();
				// 获取到选中的位置 修改对应位置的下载状态(显示状态)
				int position = entry.getKey();
				OfflineCache offlineCache = mCacheTVSelectionData.get(position);
				offlineCache
						.setCacheDownloadState(OfflineCache.CACHE_STATE_QWAITING);
				offlineCache.setCacheStoragePath(SystemUtil.getInstance()
						.getOfflineCachePath());
				// 来源名称
				offlineCache.setCacheSourceName(mSourceName);
				offlineCache
						.setCacheFromPage(OfflineCache.CACHE_FROM_PAGE_MORE);
				tmpAddCacheList.add(mCacheTVSelectionData.get(position));
				L.v("JasonZue",
						"添加到缓存列表的数据:"
								+ mCacheTVSelectionData.get(position)
										.toString());
			}
			// 清空选中状态(否则界面不会变化 )

			if (tmpAddCacheList.size() == 0) {
				FoneUtil.showToast(mContext, R.string.cache_selete_no_data_text);
				return;
			} else {
				if (SystemUtil.getInstance().isUpperLimitSpace()) {
					// 判断是否到达可使用容量下线
					FoneUtil.showToast(mContext, R.string.cache_no_memory_text);
					return;
				}
				// 无网情况下不允许添加缓存
				mGridAdatper.cancleSeleted();
				mGridAdatper.notifyDataSetInvalidated();
				mGridVarityAdatper.cancleSeleted();
				mGridVarityAdatper.notifyDataSetInvalidated();
				Toast.makeText(mContext, "已添加选中项到下载列表", Toast.LENGTH_SHORT)
						.show();
				mDeleteBt.setText("确定");
				mDeleteBt.setTextColor(mContext.getResources().getColor(
						R.color.btn_unpress_text_color));

				// 将选中的剧集添加到缓存列表中
				StorageModule.getInstance().addCacheList(tmpAddCacheList);
			}
			break;
		case TV_MANAGEMENT_MODE:

			// 电视剧管理界面删除逻辑
			List<OfflineCache> tvDeletList = new ArrayList<OfflineCache>();
			for (int i = mOfflineCacheFileList.size(); i > 0; i--) {
				if (mOfflineCacheFileList.get(i - 1).getCacheIsDelete()) {
					// 将需要移除的数据存放在临时删除表里
					tvDeletList.add(mOfflineCacheFileList.get(i - 1));
					mOfflineCacheFileList.remove(i - 1);
				}
			}

			if (tvDeletList.size() == 0) {
				FoneUtil.showToast(mContext,
						R.string.cache_no_seleted_video_text);
				return;
			}
			isDeleting = true;// 删除操作标记 (用于处理返回键屏蔽)
			L.v("JasonZue",
					"TV_MANAGEMENT_MODE 删除的数据:" + tvDeletList.toString());
			StorageModule.getInstance().deleteCacheList(tvDeletList);

			showWaiting(DELETE_WAITING);
			mDeleteBt.setText(getResources().getString(
					R.string.cache_title_right_delete_text));
			mDeleteBt.setTextColor(mContext.getResources().getColor(
					R.color.btn_unpress_text_color));
			mSelectAllBt.setText(getResources().getString(
					R.string.cache_select_all_text));

			break;
		}
	}

	/**
	 * 获取更多剧集列表
	 * 
	 * @return void
	 * @throws
	 */
	private void doMoreDrama(String dramaUrl) {

		showWaiting(REQUEST_WAITING);
		// 请求对应的剧集列表
		L.v(TAG, "doMoreDrama", "剧集请求接口:" + dramaUrl);
		if (FoneUtil.isNetOkWithToast(mContext) && !TextUtils.isEmpty(dramaUrl)) {
			Request.getInstance().drama(dramaUrl, dramaCallback);
		} else {
			L.e(TAG, "doMoreDrama", "dramaUrl==null!!!");
			cancelWaiting(REQUEST_WAITING);
			FoneUtil.showToast(mContext,
					R.string.cache_cannot_get_more_drama_text);
		}
	}

	/**
	 * 根据当前视图模式管理返回事件
	 * 
	 * @return void
	 * @throws
	 */
	private void returnBtManage() {
		switch (ViewMode) {
		case NORMAL_MODE:
			// 普通模式返回退出上级页面
			finish();
			break;
		case MANAGEMENT_MODE:
			// 管理模式返回退回到普通模式
			L.v("JasonZue", "MANAGEMENT_MODE 点击返回时的删除状态" + isDeleting);
			if (!isDeleting) {
				change2Normal();
				// 清空删除数据
				for (int i = 0; i < mOfflineCacheFolderList.size(); i++) {
					mOfflineCacheFolderList.get(i).setCacheIsDelete(false);
				}
				// 再次刷新数据
				L.v("JasonZue", "MANAGEMENT_MODE返回到普通模式,重新获取folder列表");
				StorageModule.getInstance().getCacheFolderList();
			}
			break;
		case TV_MANAGEMENT_MODE:
			// 电视剧管理模式 返回到电视剧列表
			L.v(TAG, "TV_MANAGEMENT_MODE 点击返回时的删除状态" + isDeleting);
			if (!isDeleting) {
				change2TvList();
				for (int i = 0; i < mOfflineCacheFileList.size(); i++) {
					mOfflineCacheFileList.get(i).setCacheIsDelete(false);
				}
				L.v(TAG, "TV_MANAGEMENT_MODE返回到TVlist模式,重新获取file列表");
				StorageModule.getInstance().getCacheFileListByCCID(dramaCCID);
			}
			break;
		case TV_SELECT_MODE:
			// 电视剧选集下载 返回到电视剧列表
			change2TvList();
			if (dramaCCID != -1) {
				// 根据ccid刷新页面
				L.v("JasonZue", "TV_SELECT_MODE返回到TVlist模式,重新获取file列表");
				StorageModule.getInstance().getCacheFileListByCCID(dramaCCID);
			}
			// 取消转圈
			mWaitingRl.setVisibility(View.GONE);
			break;
		case TV_SERISE_MODE:
			// 电视剧列表返回到普通模式
			change2Normal();
			L.v("JasonZue", "TV_SERISE_MODE返回到normol模式,重新获取folder列表");
			StorageModule.getInstance().getCacheFolderList();
			// 取消转圈
			mWaitingRl.setVisibility(View.GONE);
			break;
		}
		// 文字颜色修改 (点击返回时 均为未选中色)
		mDeleteBt.setTextColor(mContext.getResources().getColor(
				R.color.btn_unpress_text_color));
		mSelectAllBt.setTextColor(mContext.getResources().getColor(
				R.color.btn_unpress_text_color));

	}

	/**
	 * 切换到普通模式
	 * 
	 * @return void
	 * @throws
	 */
	private void change2Normal() {
		// 开始所有下载 界面刷新
		StorageModule.getInstance().startSendOfflineCacheMessage();
		ViewMode = NORMAL_MODE;
		L.v("JasonZue", "我的缓存--->当前在普通页面");
		mDeleteLl.setVisibility(View.GONE);
		mStorageInfoRl.setVisibility(View.VISIBLE);
		mStorageRl.setVisibility(View.VISIBLE);
		mDownloadMoreBt.setVisibility(View.GONE);
		mAutoCacheRl.setVisibility(View.VISIBLE);
		mAutoDownloadCb.setVisibility(View.VISIBLE);
		mDownloadTextTv.setText(getResources().getString(
				R.string.cache_wifi_switch_tip_text));
		mRightBt.setText(getResources().getString(
				R.string.cache_title_right_delete_text));
		mLeftBt.setText(getResources().getString(R.string.cache_title_text));
		mSelectAllBt.setText(getResources().getString(
				R.string.cache_select_all_text));
		mCacheListView.setAdapter(mOfflineCacheFolderAdatper);
		// 更新容量大小
		StorageModule.getInstance().checkSingleStorageSpace();
		// 文字颜色修改 (点击返回时 均为未选中色)
		mDeleteBt.setTextColor(mContext.getResources().getColor(
				R.color.btn_unpress_text_color));
		mSelectAllBt.setTextColor(mContext.getResources().getColor(
				R.color.btn_unpress_text_color));
		mDramaUrl = "";
		if (mOfflineCacheFolderList.size() == 0) {
			mNodateRl.setVisibility(View.VISIBLE);
		}
	}

	/**
	 * 切换到管理模式
	 * 
	 * @return void
	 * @throws
	 */
	private void change2Manage() {
		// 暂停所有下载 停止界面刷新
		StorageModule.getInstance().stopSendOfflineCacheMessage();

		ViewMode = MANAGEMENT_MODE;
		L.v("JasonZue", "我的缓存--->当前在管理页面");
		mDeleteLl.setVisibility(View.VISIBLE);
		mSelectAllBt.setText(getResources().getString(
				R.string.cache_select_all_text));
		mDeleteBt.setText(getResources().getString(
				R.string.cache_title_right_delete_text));
		mStorageInfoRl.setVisibility(View.GONE);
		mStorageRl.setVisibility(View.VISIBLE);
		mDownloadMoreBt.setVisibility(View.GONE);
		mAutoDownloadCb.setVisibility(View.GONE);
		mDownloadTextTv.setText(getResources().getString(
				R.string.cache_select_delete_tip_text));
		mAutoCacheRl.setVisibility(View.VISIBLE);
		mRightBt.setText(getResources().getString(
				R.string.cache_title_right_cancel_text));
		mLeftBt.setText(getResources().getString(R.string.cache_title_text));

		mCacheListView.setAdapter(mOfflineCacheFolderManageAdatper);
		mOfflineCacheFolderManageAdatper
				.setOfflineCacheList(mOfflineCacheFolderList);
		mOfflineCacheFolderManageAdatper.notifyDataSetChanged();

	}

	/**
	 * 切换到电视剧管理模式
	 * 
	 * @return void
	 * @throws
	 */
	private void change2TVManage() {
		// 暂停所有下载 停止界面刷新
		StorageModule.getInstance().stopSendOfflineCacheMessage();
		isSelectedAll = false;// 清除全选记录状态
		ViewMode = TV_MANAGEMENT_MODE;
		L.v("JasonZue", "我的缓存--->当前在TV管理页面");
		mDeleteLl.setVisibility(View.VISIBLE);
		mSelectAllBt.setText(getResources().getString(
				R.string.cache_select_all_text));
		mDeleteBt.setText(getResources().getString(
				R.string.cache_title_right_delete_text));

		mStorageInfoRl.setVisibility(View.GONE);
		mStorageRl.setVisibility(View.VISIBLE);
		mDownloadMoreBt.setVisibility(View.GONE);
		mAutoDownloadCb.setVisibility(View.GONE);
		mDownloadTextTv.setText(getResources().getString(
				R.string.cache_select_delete_tip_text));
		mAutoCacheRl.setVisibility(View.VISIBLE);
		mRightBt.setText(getResources().getString(
				R.string.cache_title_right_cancel_text));
		mLeftBt.setText(mDramaName);
		mCacheListView.setAdapter(mOfflineCacheFileManageAdatper);
		mOfflineCacheFileManageAdatper
				.setOfflineCacheList(mOfflineCacheFileList);
		mOfflineCacheFileManageAdatper.notifyDataSetChanged();
	}

	/**
	 * 切换到tv列表模式
	 * 
	 * @return void
	 * @throws
	 */
	private void change2TvList() {
		ViewMode = TV_SERISE_MODE;
		L.v("JasonZue", "我的缓存--->当前在tv页面");
		L.v("JasonZue",
				"time of arrived in TV_SERISE_MODE from NORMAL_MODE(change2TvList):"
						+ System.currentTimeMillis());
		// 开始所有下载 界面刷新
		StorageModule.getInstance().startSendOfflineCacheMessage();
		mPageInfoSv.setVisibility(View.GONE);
		mDeleteLl.setVisibility(View.GONE);
		mStorageInfoRl.setVisibility(View.VISIBLE);
		mStorageRl.setVisibility(View.GONE);
		mAutoCacheRl.setVisibility(View.VISIBLE);
		mRightBt.setText(getResources().getString(
				R.string.cache_title_right_delete_text));
		mLeftBt.setText(mDramaName);
		mDownloadTextTv.setText(getResources().getString(
				R.string.cache_wifi_switch_tip_text));
		mAutoDownloadCb.setVisibility(View.VISIBLE);
		mRightBt.setVisibility(View.VISIBLE);
		mCacheListView.setVisibility(View.VISIBLE);
		mCacheGridView.setVisibility(View.GONE);
		mCacheGridVarietyView.setVisibility(View.GONE);

		// 文字颜色修改 (点击返回时 均为未选中色)
		mDeleteBt.setTextColor(mContext.getResources().getColor(
				R.color.btn_unpress_text_color));
		mSelectAllBt.setTextColor(mContext.getResources().getColor(
				R.color.btn_unpress_text_color));
		// 清除40宫格勾选状态
		mGridAdatper.cancleSeleted();
		mGridVarityAdatper.cancleSeleted();
		refreshPageView();
		L.v("JasonZue", "TVlist:-------->数据长度:" + mOfflineCacheFileList.size());
		if (mOfflineCacheFileList.size() > 0) {
			mDownloadMoreBt.setVisibility(View.VISIBLE);
			mRightBt.setVisibility(View.VISIBLE);
		} else {
			mDownloadMoreBt.setVisibility(View.GONE);
			mRightBt.setVisibility(View.INVISIBLE);
		}
		// 选中页初始化为0 防止空指针崩溃
		selectedPageNum = 0;
		// 重置列表选中头位置为0
		mPageAdapter.resetSelectedPostion();

		// 刷新数据
		mOfflineCacheFileAdapter.setOfflineCacheList(mOfflineCacheFileList);
		mCacheListView.setAdapter(mOfflineCacheFileAdapter);
		mOfflineCacheFileAdapter.notifyDataSetChanged();
	}

	/**
	 * 切换到tv剧集grid模式
	 * 
	 * @return void
	 * @throws
	 */
	private void change2TvGrid(boolean isRegular) {
		isSelectedAll = false;
		StorageModule.getInstance().stopSendOfflineCacheMessage();
		ViewMode = TV_SELECT_MODE;
		L.v("JasonZue", "我的缓存--->当前在剧集下载更多页面");
		// 设置分页
		mCacheListView.setVisibility(View.INVISIBLE);
		mPageInfoSv.setVisibility(View.VISIBLE);
		mPageAdapter.notifyDataSetChanged();
		refreshPageView();
		if (isRegular) {
			mCacheGridView.setVisibility(View.VISIBLE);
			mCacheGridVarietyView.setVisibility(View.GONE);
			mCacheGridView.setAdapter(mGridAdatper);
		} else {
			mCacheGridView.setVisibility(View.GONE);
			mCacheGridVarietyView.setVisibility(View.VISIBLE);
			mCacheGridVarietyView.setAdapter(mGridVarityAdatper);
		}
		mDeleteLl.setVisibility(View.VISIBLE);
		mSelectAllBt.setText(getResources().getString(
				R.string.cache_title_right_cancel_text));
		mDeleteBt.setText("确定");

		mStorageInfoRl.setVisibility(View.GONE);
		mStorageRl.setVisibility(View.VISIBLE);
		mDownloadMoreBt.setVisibility(View.GONE);
		mAutoCacheRl.setVisibility(View.GONE);
		mLeftBt.setText("选择您要缓存的剧集");
		mRightBt.setVisibility(View.GONE);

	}

	/**
	 * 更新管理界面底部删除文字变化
	 * 
	 * @param position
	 * @param mBox
	 * @return void
	 * @throws
	 */
	private void updateManagerDeleteInfo(int position, CheckBox mBox,
			List<OfflineCache> mData, int count) {
		mData.get(position - 1).setCacheIsDelete(
				!mData.get(position - 1).getCacheIsDelete());
		mBox.setChecked(mData.get(position - 1).getCacheIsDelete());
		count = 0;
		for (int i = 0; i < mData.size(); i++) {
			if (mData.get(i).getCacheIsDelete()) {
				count++;
			}
		}
		if (count == 0) {

			mDeleteBt.setText(getResources().getString(
					R.string.cache_title_right_delete_text));
			mDeleteBt.setTextColor(mContext.getResources().getColor(
					R.color.btn_unpress_text_color));
		} else {
			mDeleteBt.setText(getResources().getString(
					R.string.cache_title_right_delete_text)
					+ "(" + count + ")");
			mDeleteBt.setTextColor(mContext.getResources().getColor(
					R.color.btn_pressed_text_color));
		}

		if (mData.size() == count) {
			mSelectAllBt.setText(getResources().getString(
					R.string.cache_cancel_all_text));
			isSelectedAll = true;
		} else {
			mSelectAllBt.setText(getResources().getString(
					R.string.cache_select_all_text));
			isSelectedAll = false;

		}
	}

	@Override
	public void onScroll(AbsListView view, int firstVisibleItem,
			int visibleItemCount, int totalItemCount) {

	}

	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {

	}

	@Override
	public void onRefresh() {

	}

	@Override
	public void onLoadMore() {

	}

	/**
	 * 剧集请求回调
	 * 
	 * @author JasonZue
	 * @since 2014-5-24
	 */
	private class DramaCallback implements Callback<DramaRst> {

		private static final String TAG = "DramaCallback";

		@Override
		public void onSuccess(DramaRst t) {
			// 请求成功 切换界面
			if (t.result == 0) {
				L.v("JasonZue", "缓存剧集中dramaCallback onSuccess:" + t.toString());

				if (null != t.cntsList) {
					if (t.cntsList.get(t.rp.p - 1).showtyp == 0) {
						change2TvGrid(true);
						isRegular = true;
					} else {
						change2TvGrid(false);
						isRegular = false;
					}
				}
				// mWaitingRl.setVisibility(View.GONE);
				cancelWaiting(REQUEST_WAITING);
				/************** 处理grid电视剧缓存列表 分页头数据 ***************************************/
				mHorizontalDate.removeAll(mHorizontalDate);
				// 判空
				if (null != t.cntsList) {
					for (int i = 0; i < t.cntsList.size(); i++) {
						mHorizontalDate.add(t.cntsList.get(i));
					}
				}
				// 根据分页数量判断是否显示分页条
				if (mHorizontalDate.size() < 2) {
					mPageInfoSv.setVisibility(View.GONE);
				} else {
					mPageInfoSv.setVisibility(View.VISIBLE);
				}
				// 更新分页顶部条显示
				mPageAdapter.notifyDataSetChanged();
				refreshPageView();
				/************** 处理grid电视剧缓存列表数据 ****************************************/
				// 清空列表
				mCacheTVSelectionData.clear();
				// 添加列表新数据(默认第一页数据)
				List<OfflineCache> dramaTmpData = new ArrayList<OfflineCache>();// 临时存储数据表
				// 需要传入到数据库中做查询下载状态.
				if (selectedPageNum > t.cntsList.size()) {
					L.e(TAG, "DramaCallback-->onSuccess",
							"title index size error!!!!! 标题选择数组越界");
					return;
				}
				for (int i = 0; i < t.cntsList.get(selectedPageNum).cntList
						.size(); i++) {

					OfflineCache itemBean = new OfflineCache();
					// 保证数据库中数据一致 添加第xxx集 使用的时候如果不需要 则截取
					itemBean.setCacheContentType(t.favtyp);
					itemBean.setCacheName(t.name);
					itemBean.setSortIndex(t.cntsList.get(t.rp.p - 1).cntList
							.get(i).idx);
					if (t.favtyp == OfflineCache.CACHE_CONTENT_TYPE_ANIMATION
							|| t.favtyp == OfflineCache.CACHE_CONTENT_TYPE_TV) {
						itemBean.setCacheEpisodeNum("第"
								+ t.cntsList.get(t.rp.p - 1).cntList.get(i).name
								+ "集");
					} else if (t.favtyp == OfflineCache.CACHE_CONTENT_TYPE_VARIETY) {
						itemBean.setCacheEpisodeNum(t.cntsList.get(t.rp.p - 1).cntList
								.get(i).name);
					}
					itemBean.setCacheXYZPlayUrl(t.cntsList.get(selectedPageNum).cntList
							.get(i).url);
					itemBean.setCacheImageUrl(t.shost
							+ FoneUtil.formatUrl(t.cntsList.get(t.rp.p - 1).cntList
									.get(i).pic));
					itemBean.setCacheIsDownloadable(t.cntsList
							.get(selectedPageNum).cntList.get(i).btndown == 0 ? false
							: true);
					itemBean.setCacheFromPage(OfflineCache.CACHE_FROM_PAGE_MORE);
					NetCollectionActivity.formatIDS(itemBean,
							t.cntsList.get(t.rp.p - 1).cntList.get(i).url);
					dramaTmpData.add(itemBean);
				}

				// 传入数据库 并获取返回的list 添加到mCacheTVSelectionData中

				List<OfflineCache> mergeOfflineCacheDownloadState = StorageModule
						.getInstance().mergeMoreDramaDownloadStateByCID(
								dramaTmpData);

				for (int i = 0; i < mergeOfflineCacheDownloadState.size(); i++) {
					L.v("JasonZue", "下载剧集号"
							+ i
							+ "---状态:"
							+ mergeOfflineCacheDownloadState.get(i)
									.getCacheDownloadState());
				}

				mCacheTVSelectionData.addAll(StorageModule.getInstance()
						.mergeMoreDramaDownloadStateByCID(dramaTmpData));
				/************ 更新剧集非规则剧集 **********************************/
				mGridVarityAdatper.notifyDataSetChanged();
				mGridAdatper.notifyDataSetChanged();
			} else {
				FoneUtil.showToast(mContext,
						R.string.cache_cannot_get_data_text);
				cancelWaiting(REQUEST_WAITING);
				change2TvList();
			}
		}

		@Override
		public void onFailure(Error error) {
			L.v(TAG,
					"DramaCallback onFailure",
					"isNetworkError : " + error.isNetworkError() + " status : "
							+ error.getStatus() + " reason : "
							+ error.getReason());
			cancelWaiting(REQUEST_WAITING);
			FoneUtil.showToast(mContext, R.string.cache_cannot_get_data_text);
			// 清空当前选项页面
			mCacheTVSelectionData.removeAll(mCacheTVSelectionData);
			mGridAdatper.notifyDataSetChanged();
			mGridVarityAdatper.notifyDataSetChanged();
			change2TvList();
		}

	}

	@Override
	protected void onResume() {
		super.onResume();
		StorageModule.getInstance().startSendOfflineCacheMessage();
		// 初始化存储空间信息
		StorageModule.getInstance().checkSingleStorageSpace();
	}

	@Override
	protected void onPause() {
		super.onPause();
		StorageModule.getInstance().stopSendOfflineCacheMessage();

	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		EventBus.getDefault().unregister(this);
	}

	/**
	 * 开始缓存所有文件
	 * 
	 * @return void
	 */
	public void startAllCache() {
		// 判断网络
		if (FoneUtil.isNetOkWithToast(mContext)) {
			long freeSpace = isMounted == true ? (SystemUtil.getInstance()
					.getFreeSpaceByteBySDCard()) : (SystemUtil.getInstance()
					.getFreeSpaceByteByPhoneBody());
			// 判断容量
			if (freeSpace < SharedPreferenceModule.getInstance().getLong(
					FoneConstant.TMP_LIMIT_SIZE)) {
				FoneUtil.showToast(mContext, R.string.cache_no_memory_text);
			} else {
				// 开始所有下载
				StorageModule.getInstance().startAllCache();
			}
		}
	}

	public void showWaiting(int waitingFlag) {

		mWaitingFlag = waitingFlag;
		dialog.showWaitingDialog();
	}

	public void cancelWaiting(int waitingFlag) {

		if (mWaitingFlag == waitingFlag) {
			dialog.cancelWaitingDialog();
			mWaitingFlag = 0;
		}

	}

	/**
	 * 播放当前选中的视频,并处理下一首(已完成的视频数据)
	 * 
	 * @param currentOfflineCache
	 *            当前选中的数据
	 * @param finishedVideos
	 *            已完成的数据list
	 * @return void
	 * @throws
	 */
	private void openSeletedVideoBySortIndex(OfflineCache currentOfflineCache,
			ArrayList<OfflineCache> finishedVideos) {
		int index = 0;
		ArrayList<CacheVideo> videos = new ArrayList<CacheVideo>();
		// 处理已缓存的数量 并完成集合
		for (int i = 0; i < finishedVideos.size(); i++) {
			OfflineCache cache = finishedVideos.get(i);
			if (cache.getCacheCID() == currentOfflineCache.getCacheCID()) {
				index = i;
			}
			String videoName = "";
			if (cache.getCacheContentType() == OfflineCache.CACHE_CONTENT_TYPE_ANIMATION
					|| cache.getCacheContentType() == OfflineCache.CACHE_CONTENT_TYPE_TV
					|| cache.getCacheContentType() == OfflineCache.CACHE_CONTENT_TYPE_VARIETY) {
				videoName = cache.getCacheName()
						+ finishedVideos.get(i).getCacheEpisodeNum();
			} else {
				videoName = cache.getCacheName();

			}
			L.v("JasonZue", "已完成的剧集名称:" + videoName);
			CacheVideo cacheVideo = new CacheVideo();
			cacheVideo.setName(videoName);
			cacheVideo.setDurations(finishedVideos.get(i)
					.getOfflineCacheFragmentDurationArray());
			cacheVideo.setPic(finishedVideos.get(i).getCacheImageUrl());
			cacheVideo.setUrls(finishedVideos.get(i)
					.getOfflineCacheFragmentUrlArray());
			cacheVideo.setXyzplay(finishedVideos.get(i).getCacheXYZPlayUrl());
			cacheVideo
					.setDownFinish(cache.getCacheDownloadState() == OfflineCache.CACHE_STATE_FINISH ? true
							: false);
			videos.add(cacheVideo);

		}
		if (videos.size() > 0) {
			L.v(TAG, "已完成播放数据(处理后):" + videos.get(index).toString());
			FoneUtil.openCacheVideo(CacheActivity.this, PlayerFrom.CACHE_LIST,
					videos, index);
			L.v("JasonZue", "time of jump to fonePlayActivity from cache:"
					+ System.currentTimeMillis());
		} else {
			L.v(TAG, "已完成播放数据(处理后):videos.size()=" + videos.size());
			FoneUtil.showToast(mContext, R.string.cache_no_finished_video_text);
		}

	}

}
